<template>
  <div class="picupload">
    <div class="user-info-head" @click="editCropper()"><img v-bind:src="options.img|splitImgSrcFirst" title="点击上传头像" :style="style" class="img-lg" /></div>
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body @opened="modalOpened"  @close="closeDialog()">
      <el-row>
        <el-col :xs="24" :md="12" :style="{height: '350px'}">
          <vue-cropper
            ref="cropper"
            :img="options.img"
            :info="true"
            :autoCrop="options.autoCrop"
            :autoCropWidth="options.autoCropWidth"
            :autoCropHeight="options.autoCropHeight"
            :fixedBox="options.fixedBox"
            @realTime="realTime"
            v-if="visible"
          />
        </el-col>
        <el-col :xs="24" :md="12" style="overflow: hidden; padding: 20px;box-sizing: border-box;" :style="{height: '350px'}">
          <div class="avatar-upload-preview" :style="style">
            <img v-show="!takingpictures" :src="previews.url" :style="previews.img" />
            <video
                v-show="takingpictures"
                ref="videoCamera"
                id="videoCamera"
                :height='height' :width="width"
                autoplay
            ></video>
            <canvas
                ref="canvasCamera"
                id="canvasCamera"
                style="display:none;"
                :width="width"
                :height="height"
            ></canvas>
          </div>
          <div class="clearfix"></div>
          <el-button icon="el-icon-camera-solid" size="small" v-if="takingpictures && type == 2"  @click="setImage()">照相</el-button>
        </el-col>
      </el-row>
      <br />
      <el-row>
        <el-col :lg="2" :md="2">
          <el-upload action="#" :http-request="requestUpload" :show-file-list="false" :before-upload="beforeUpload">
            <el-button size="small" @click="type == 2 ? stopNavigator() : type = 1">选择 <i class="el-icon-upload el-icon--right"></i></el-button>
          </el-upload>
        </el-col>
        <el-col :lg="{span: 1, offset: 1}" :md="2">
          <el-button icon="el-icon-camera-solid" size="small" @click="getCompetence()">拍照 </el-button>
        </el-col>
        <el-col :lg="{span: 1, offset: 2}" :md="2">
          <el-button icon="el-icon-plus" size="small" @click="changeScale(1)"></el-button>
        </el-col>
        <el-col :lg="{span: 1, offset: 1}" :md="2">
          <el-button icon="el-icon-minus" size="small" @click="changeScale(-1)"></el-button>
        </el-col>
        <el-col :lg="{span: 1, offset: 1}" :md="2">
          <el-button icon="el-icon-refresh-left" size="small" @click="rotateLeft()"></el-button>
        </el-col>
        <el-col :lg="{span: 1, offset: 1}" :md="2">
          <el-button icon="el-icon-refresh-right" size="small" @click="rotateRight()"></el-button>
        </el-col>
        <el-col :lg="{span: 2, offset: 6}" :md="2">
          <el-button type="primary" size="small" @click="uploadImg()">提 交</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import store from "@/store";
import { VueCropper } from "vue-cropper";
import { uploadAvatar } from "@/api/system/user";
import request from '@/utils/request'

export default {
  components: { VueCropper },
  props: {
    width:{
      type:Number | String,
      default:200
    },
    height:{
      type:Number | String,
      default:200
    },
    src:{
      // 图片路径
      type:String
    },
    httpRequest:{
      // api请求地址
      type:String
    },
    clip:{
      // 裁剪图片
      type:Boolean,
      default:true
    }
  },
  data() {
    return {
      takingpictures:false,
      type:1,//1 上传，2拍照
      // 是否显示弹出层
      open: false,
      // 是否显示cropper
      visible: false,
      // 弹出层标题
      title: "修改头像",
      options: {
        img: this.src, //裁剪图片的地址
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: this.width, // 默认生成截图框宽度
        autoCropHeight: this.height, // 默认生成截图框高度
        fixedBox: this.clip // 固定截图框大小 不允许改变
      },
      previews: {}
    };
  },
  computed:{
    style(){
      return {
        'width': this.width + 'px',
        'height': this.height + 'px'
      }
    }
  },
  watch:{
    src(v){
      this.options.img=v
    }
  },
  methods: {
    // 编辑头像
    editCropper() {
      this.open = true;
    },
    // 打开弹出层结束时的回调
    modalOpened() {
      this.visible = true;
    },
    // 覆盖默认的上传行为
    requestUpload() {
    },
    // 向左旋转
    rotateLeft() {
      this.$refs.cropper.rotateLeft();
    },
    // 向右旋转
    rotateRight() {
      this.$refs.cropper.rotateRight();
    },
    // 图片缩放
    changeScale(num) {
      num = num || 1;
      this.$refs.cropper.changeScale(num);
    },
    // 上传预处理
    beforeUpload(file) {
      if (file.type.indexOf("image/") == -1) {
        this.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
      } else {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          this.options.img = reader.result;
        };
      }
    },
    // 上传图片
    uploadImg() {
      this.$refs.cropper.getCropBlob(data => {
        let formData = new FormData();
        formData.append('file',data,new Date().getTime()+".jpg")
        request({
          url: this.httpRequest,
          method: 'post',
          data: formData
        }).then(response => {
          this.open = false;
          this.options.img = response.fileName;
          this.$emit("update:src",response.fileName)
          this.msgSuccess("修改成功");
          this.visible = false;
        })
      });
    },
    // 实时预览
    realTime(data) {
      this.previews = data;
    },
    // 关闭窗口
    closeDialog() {
      this.options.img = this.src;
      this.visible = false;
      if(this.type == 2){
        this.stopNavigator();
      }
    },
    // 调用权限（打开摄像头功能）
    getCompetence() {
      var _this = this;
      this.takingpictures = true;
      this.type = 2;
      _this.thisCancas = this.$refs.canvasCamera;
      _this.thisContext = this.thisCancas.getContext('2d');
      _this.thisVideo =  this.$refs.videoCamera;
      _this.thisVideo.style.display = 'block';
      // 获取媒体属性，旧版本浏览器可能不支持mediaDevices，我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
      }
      // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
      // 使用getUserMedia，因为它会覆盖现有的属性。
      // 这里，如果缺少getUserMedia属性，就添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function(constraints) {
          // 首先获取现存的getUserMedia(如果存在)
          var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia;
          // 有些浏览器不支持，会返回错误信息
          // 保持接口一致
          if (!getUserMedia) {
            // 不存在则报错
            return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
          }
          // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
          return new Promise(function(resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject);
          });
        };
      }
      var constraints = {
        audio: false,
        video: {
          width: this.width,
          height: this.height,
          transform: 'scaleX(-1)'
        }
      };
      navigator.mediaDevices
        .getUserMedia(constraints)
        .then(function(stream) {
          // 旧的浏览器可能没有srcObject
          if ('srcObject' in _this.thisVideo) {
            _this.thisVideo.srcObject = stream;
          } else {
            // 避免在新的浏览器中使用它，因为它正在被弃用。
            _this.thisVideo.src = window.URL.createObjectURL(stream);
          }
          _this.thisVideo.onloadedmetadata = function(e) {
            _this.thisVideo.play();
          };
        })
        .catch(err => {
          console.log(err);
        });
    },
    //  绘制图片（拍照功能）
    setImage() {
      var _this = this;
      // canvas画图
      _this.thisContext.drawImage(_this.thisVideo, 0, 0, _this.width, _this.height);
      // 获取图片base64链接
      var image = this.thisCancas.toDataURL('image/png');
      // _this.previews.url = image;// 赋值并预览图片
      this.options.img = image
      // var fileData =this.dataURLtoFile(_this.imgSrc,'image/jpeg');
      // let form = new FormData();
      // form.append("bizType","9");
      // let fileOfBlob = new File([fileData], new Date()+'.jpg'); // 重命名了
      // form.append("file", fileOfBlob);
      this.stopNavigator();
      this.takingpictures = false
    },
    // 关闭摄像头
    stopNavigator() {
      this.type = 1;
      this.takingpictures = false
      this.thisVideo.srcObject.getTracks()[0].stop();
    },
  //将base64转换为blob
    dataURLtoFile(dataURI, type) {
      let binary = atob(dataURI.split(',')[1]);
      let array = [];
      for(let i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
      }
      return new Blob([new Uint8Array(array)], {type:type });
    }
  }
};
</script>
<style scoped lang="scss">
.user-info-head {
  position: relative;
  display: inline-block;
  overflow: hidden;
  // height: 120px;
}

.user-info-head:hover:after {
  content: '+';
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  color: #eee;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, 0.5);
  font-size: 24px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  cursor: pointer;
  // border-radius: 50%;
}
.avatar-upload-preview{
  overflow: hidden;
  box-shadow: 0 0 4px #ccc;
}
</style>
